<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-03-17 15:38:54
 * @Description  : 用户空间使用的饼图
-->

<template>
  <div
    :class="
      size === 'small'
        ? ['wrap', 'min-w-[300px]', 'w-[400px]', 'h-[400px]']
        : ['wrap', 'min-w-[300px]', 'w-[500px]', 'h-[500px]']
    "
  >
    <div
      class="chart w-[100%] h-[100%] flex justify-center items-center"
      :id="chartId"
    ></div>
    <n-divider />
    <div class="flex justify-center">
      <div>
        总使用量: <b>{{ convertFromBytes('' + spaceTotalInfo.totalSize) }}</b>
      </div>
      <div class="ml-10">
        文件数:<b>{{ spaceTotalInfo.total }}</b>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { getSpaceChart } from '@/api/overview'
import { getUserSpaceChart } from '@/api/user'
import type { IndexObj } from '@/types/commom'
import type { SpaceChartRes } from '@/types/overview'
import { convertFromBytes } from '@/utils'
import { pieChartItemStyles } from '@/constants/charts'

const props = withDefaults(
  defineProps<{
    targetId: string
    targetType: number
    chartId: string
    subTitle?: string
    isAdmin?: boolean
    size?: 'small' | 'large'
  }>(),
  {
    isAdmin: true,
    size: 'small'
  }
)

onMounted(() => {
  initEcharts()
  if (!props.isAdmin) {
    loadSpaceChart()
    return
  }

  if (props.targetId !== '-1' && props.isAdmin) {
    loadSpaceChart()
  }
})

const spaceTotalInfo = reactive({
  total: 0,
  totalSize: 0
})

watch(
  () => props.targetId,
  (newValue) => {
    if (!props.isAdmin) {
      loadSpaceChart()
      return
    }

    if (newValue !== '-1' && props.isAdmin) {
      loadSpaceChart()
    }
  },
  {
    deep: true
  }
)

// 重新加载用户空间图表饼图
const loadSpaceChart = () => {
  if (props.isAdmin) {
    getSpaceChart({
      targetType: props.targetType,
      targetId: props.targetId
    })
      .then((res) => {
        afterAction(res.data)
      })
      .catch(console.error)
      .finally(() => {})
  } else {
    getUserSpaceChart()
      .then((res) => {
        afterAction(res.data)
      })
      .catch(console.error)
  }
}

const afterAction = (res: SpaceChartRes) => {
  const totalInfo = res.items.reduce(
    (pre, cur) => {
      pre.total += cur.total
      pre.totalSize += cur.totalSize
      return pre
    },
    { total: 0, totalSize: 0 }
  )
  spaceTotalInfo.total = totalInfo.total
  spaceTotalInfo.totalSize = totalInfo.totalSize
  baseChartOption.value.series[0].data = res.items.map((item, i) => {
    return {
      name: item.name,
      value: item.total,
      size: item.totalSize,
      itemStyle: { color: pieChartItemStyles[i] }
    }
  })
  baseChartOption.value.title.subtext = props.subTitle || ''
  myChart.value.setOption(baseChartOption.value)
}

const baseChartOption = ref({
  title: {
    text: '空间使用',
    left: 'left',
    subtext: ''
  },
  tooltip: {
    trigger: 'item',
    formatter: function (params: IndexObj) {
      return `${params.name}: ${params.value} (${
        params.percent
      }%) (${convertFromBytes('' + params.data.size)})`
    }
  },
  legend: {
    orient: 'horizontal',
    left: 'center',
    bottom: '0'
  },
  series: [
    {
      name: '',
      type: 'pie',
      radius: ['25%', '50%'],
      labelLine: {
        show: true
      },
      data: [
        {
          size: 20,
          value: 10,
          name: '文档',
          itemStyle: { color: '#0a9afe' }
        },
        {
          size: 20,
          value: 10,
          name: '图片',
          itemStyle: { color: '#95e1e1' }
        },
        {
          size: 20,
          value: 10,
          name: '音乐',
          itemStyle: { color: '#fa90ba' }
        },
        {
          size: 20,
          value: 10,
          name: '视频',
          itemStyle: { color: '#f79992' }
        },
        {
          size: 20,
          value: 10,
          name: '压缩包',
          itemStyle: { color: '#ffe9a7' }
        },
        {
          size: 20,
          value: 1,
          name: '其他',
          itemStyle: { color: '#eceef1' }
        }
      ],
      label: {
        show: true,
        formatter: '{b}({d}%)'
      },
      emphasis: {
        itemStyle: {
          color: 'inherit',
          opactity: 0.5
        }
      }
    }
  ]
})

const myChart = ref<any>()
const initEcharts = () => {
  // 基于准备好的dom，初始化echarts实例
  myChart.value = echarts.init(document.getElementById(props.chartId))
  // 绘制图表
  myChart.value.setOption(baseChartOption.value)
}
</script>

<style scoped lang="scss">
.wrap {
  flex-direction: column;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
